package com.demo.test.juc.Atomic;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 原子引用
 * @author gy
 * @date 2023/7/29
 */
public class AtomicReferenceDemo {
    @AllArgsConstructor
    @Data
    class Book{
        String name;
        int price;
    }

    AtomicReference atomicReference = new AtomicReference<Book>();



    @Test
    public void m1() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Book mysql = new Book("mysql", 1);
        Book java = new Book("java", 2);

        CountDownLatch countDownLatch = new CountDownLatch(2);

        atomicReference.set(mysql);

        new Thread(() -> {
            System.out.println(atomicReference.compareAndSet(mysql,java));
            countDownLatch.countDown();
        },"t1").start();


        new Thread(() -> {
            System.out.println(atomicReference.compareAndSet(mysql,java));
            countDownLatch.countDown();
        },"t2").start();

        countDownLatch.await();
        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时["+(endTime - startTime)+"]毫秒");
    }



}
